# -*- coding: utf-8 -*-
import random
import scrapy
from scrapy import Request
from scrapy.exceptions import IgnoreRequest
from zc_core.spiders.base import BaseSpider
from zc_core.dao.order_pool_dao import OrderPoolDao
from zc_core.model.items import Box, OrderStatus
from zc_core.util import file_reader
from zc_core.util.http_util import retry_request
from zc_core.util.order_deadline_filter import OrderItemFilter
from esgcc.rules import *


class OrderItemFromMongoSpider(BaseSpider):
    name = 'order_item_from_mongo'
    custom_settings = {
        'CONCURRENT_REQUESTS': 3,
        'DOWNLOAD_DELAY': 0.1,
        'CONCURRENT_REQUESTS_PER_DOMAIN': 3,
        'CONCURRENT_REQUESTS_PER_IP': 3,
    }

    # 常用链接
    api_url = 'http://m.esgcc.com.cn/common/sendPostByJsonStr'

    def __init__(self, batchNo=None, *args, **kwargs):
        super(OrderItemFromMongoSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        self.order_filter = OrderItemFilter()

    def start_requests(self):
        # token = SeleniumIOSLogin().get_token()
        token = '34ea700911c74a159fdad49f85b77125'
        if not token:
            self.logger.error('init token failed...')
            return
        self.logger.info('init token: %s', token)

        # 处理订单列表
        order_list = OrderPoolDao().get_todo_list(
            batch_no=self.batch_no,
            query={'workStatus': {'$ne': 1}, 'orderTime': {'$gt': self.order_filter.get_deadline()}},
            fields={'_id': 1, 'orderTime': 1, 'orderDept': 1}
        )
        if order_list:
            self.logger.info('目标：%s' % (len(order_list)))
            random.shuffle(order_list)
            for order in order_list:
                order_id = order.get('_id')

                # 采集order明细页
                yield Request(
                    method='POST',
                    url=self.api_url,
                    headers={
                        'Host': 'm.esgcc.com.cn',
                        'Accept': 'application/json',
                        'path': '/pcenterapi/pcenter/OrderService/orderDetail',
                        'Accept-Language': 'zh-cn',
                        'Accept-Encoding': 'gzip, deflate',
                        'type': 'getUserData',
                        'token': token,
                        'User-Agent': 'e%E9%80%89%E8%B4%AD/2.3.5 CFNetwork/976 Darwin/18.2.0',
                        'Connection': 'keep-alive',
                        'Content-Type': 'application/json',
                    },
                    body='{"orderId":"%s"}' % order_id,
                    meta={
                        'reqType': 'order_item',
                        'orderId': order_id,
                    },
                    callback=self.parse_order_item_ios,
                    errback=self.error_back,
                    priority=200,
                    dont_filter=True
                )

    def parse_order_item_ios(self, response):
        meta = response.meta
        order_id = meta.get('orderId')

        # 处理订单列表
        orders, order_time = parse_order_item_ios(response)
        if orders:
            yield Box('order_item', self.batch_no, orders)

        # 标记订单已采
        order_status = OrderStatus()
        order_status['id'] = order_id
        order_status['orderTime'] = order_time
        order_status['batchNo'] = time_to_batch_no(order_time)
        order_status['workStatus'] = 1
        self.logger.info('完成: order=%s, item=%s' % (order_id, len(orders)))
        yield order_status
